package com.ruoyi.portal.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Regexregisteredservice;
import com.ruoyi.portal.service.ServicesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/portal/userServices")
public class UserServicesController extends BaseController {
  @Autowired
  ServicesService servicesService;

  //得到service
  @PreAuthorize("@ss.hasPermi('portal:userServices:listByUserId')")
  @PostMapping("/getServicesByUserId")
  public List<Regexregisteredservice> getServicesByUserId(@RequestBody String userIdStr) {
    HashMap map = JSONObject.parseObject(userIdStr, HashMap.class);
    long userId = Long.parseLong(map.get("userId").toString());
    return servicesService.getServicesByUserId(userId);
  }

  //删除指定的service
  @PreAuthorize("@ss.hasPermi('portal:userServices:delete')")
  @PostMapping("/delUserService")
  public AjaxResult delUserServiceByServiceId(@RequestBody  Map map) {
    long serviceId = Long.parseLong(map.get("serviceId").toString());
    long userId = Long.parseLong(map.get("userId").toString());
    return toAjax(servicesService.delUserServiceByServiceIdUserId(userId, serviceId));
  }

  //增加指定的service
  @PreAuthorize("@ss.hasPermi('portal:userServices:add')")
  @PostMapping("/addService")
  public AjaxResult addService(@RequestBody HashMap<String, String> map) {
    long serviceId = Long.parseLong(map.get("serviceId"));
    String username = map.get("username");
    int num = servicesService.addUserServiceByServiceIdUserId(username, serviceId);
    if (num > 0) {
      return AjaxResult.success("添加成功");
    } if(num==-1) {
      return AjaxResult.error("已经存在！");
    }
    return AjaxResult.error("添加失败");
  }
}
